# !/bin/usr/python
# _*_ coding=utf-8 _*_
# Filename : multipart_encode.py

import os
import msvcrt

# 二进制文件处理
msvcrt.setmode( 0, os.O_BINARY )

# 换行符
NEWLINE = '\r\n'

class MultipartEncode():
	"""docstring for multipartformat"""

	_BodyList = []
	_BOUNDARY = None

	def __init__(self, boundary):
		self._BOUNDARY = boundary

	def add_value(self, name, value):
		self._BodyList.append("--" + self._BOUNDARY)
		self._BodyList.append('Content-Disposition: form-data; name="%s"' % name)
		self._BodyList.append('')
		self._BodyList.append(value)

	def add_file(self, name, filename, filepath, dattype='application/octet-stream'):
		self._BodyList.append('--' + self._BOUNDARY)
		self._BodyList.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename))
		self._BodyList.append('Content-Type: %s' % dattype)
		self._BodyList.append('')
		fp = open(filepath,'rb')
		self._BodyList.append(fp.read())
		fp.close()	

	def get_body(self):
		return (NEWLINE.join(map(str, self._BodyList)) + NEWLINE + '--' + self._BOUNDARY + '--' + NEWLINE)


# try:
# 	body = MultipartEncode('----------ABCDEFG0123456789abcdefg')
# 	body.add_file('file1', 'tt.txt', 'tt.txt')
# 	body.add_file('file2', 'tt.txt', 'tt.txt')
# 	print(body.get_body())
# except Exception as ee:
# 	print ('error: %s' % str(ee))
